package com.njwb.sql;

import com.njwb.entity.Dept;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Description: 类的描述
 * Author: yuandeyin@itany.com
 * Date: 2025-08-08 15:38
 * Version: 1.0
 */
public class TestSelectList {
    public static void main(String[] args) {
        //查询所有部门

        List<Dept> deptList = new ArrayList<Dept>();
        //1.加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //2.获取连接
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://localhost:3306/db_test?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT";
        try {
            conn = DriverManager.getConnection(url,"root","root");
            //3.获取SQL执行器
            //测试可以写 * 代表所有的字段，开发的时候写上具体的字段名称
            String sql = "select deptno,dname,dloc from dept";
            pstmt = conn.prepareStatement(sql);

            //4.执行SQL
            rs = pstmt.executeQuery();//执行SELECT
            //5.反馈结果
            //.....
            while(rs.next()){//光标移动到数据的第一行
                //有一条部门数据 ----》有一个Dept对象
                Dept dept = new Dept();
                //部门对象的数据从哪里来？
                //从行记录中来
                //rs当前指定的行中取数据
                dept.setDeptNo(rs.getInt("deptno"));
                dept.setName(rs.getString("dname"));
                dept.setLoc(rs.getString("dloc"));
                deptList.add(dept);

            }
            for(Dept dept : deptList){
                System.out.println(dept);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //6.关闭资源
            if(null != rs){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(null != pstmt){
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(null != conn){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }




    }
}
